﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsAsync
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnSync_Click(object sender, EventArgs e)
        {
            lblResult.Text = "Start to do something . . .";
            long value = DoSomething(int.MaxValue / 2);
            lblResult.Text = value.ToString();
        }

        #region Do things
        public long DoSomething(int n)
        {
            long result = 1;
            for (int i = 1; i <= n; i++)
            {
                result += i;
            }
            return result;
        }
        #endregion

        private void btnCallback_Click(object sender, EventArgs e)
        {
            lblResult.Text = "Start to do something . . .";
            Func<int, long> callBackDelegate = this.DoSomething;
            callBackDelegate.BeginInvoke(
                 int.MaxValue / 2,
                 new AsyncCallback(
                 a =>
                 {
                     lblResult.Invoke(new MethodInvoker(() =>
                     {
                         lblResult.Text = callBackDelegate.EndInvoke(a).ToString();
                     }));
                 }),
                 null);
        }

        private async void btnAsync_Click(object sender, EventArgs e)
        {
            lblResult.Text = "Start to do something . . .";
            var x = await DoSomethingAsync(int.MaxValue / 2);
            lblResult.Text = x.ToString();
        }

        private Task<long> DoSomethingAsync(int n)
        {
            return Task.Run<long>(() => DoSomething(n));
        }
    }
}
